<?php

global $objApi;

$objApi->register(new Route(Api::GET, "/api/files", function($api, $self){
	$path = "/";
	if(isset($_GET["path"])){
		$path = Utils::cleanArg($_GET["path"]);
	}

	$objFs = new Filesystem();
	$id = $objFs->find($path);
	if($id == -1) {
		$api->send(array("msg" => "Not found!"), 500);
	} else {
		if($id != 0) {
			$aryDirInfo = $objFs->dirInfo($id);
		} else {
			$aryDirInfo = array("_id" => 0, "name" => "root");
		}
		$aryDirInfo["contents"] = $objFs->dirContents($id);

		//send the result
		$api->send($aryDirInfo);
	}
}));

$objApi->register(new Route(Api::POST, "/api/file/save", function($api, $self){
	global $objDatabase;

	$parent_id = Utils::cleanArg($_POST["parent_id"]);

	$fileName = $_FILES["file"]["name"]; 
	$fileTmpLoc = $_FILES["file"]["tmp_name"];
	$type = mime_content_type($fileTmpLoc);

	$sql = "INSERT INTO `amps_fs` (`parent_id`, `name`, `is_dir`, `mime`, `last_change`) "
	      ."VALUES('" . $parent_id . "','" . $fileName."','0','" . $type . "',NOW())";

	$res = $objDatabase->query($sql);
	$id = $objDatabase->lastId();

	//move the new file
	move_uploaded_file($fileTmpLoc, "/var/www/amp-storage/upload/" . $id);

	$api->send(array("_id" => $id));
}));


?>